﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ChinaDynastyTours.Models;
using DevExpress.XtraGrid.Columns;
using ChinaDynastyTours.Controls;
using ChinaDynastyTours.Helpers;
using System.Threading;

namespace ChinaDynastyTours.Views
{
    public partial class TourGroupScheduleForm : DevExpress.XtraEditors.XtraForm
    {
        public DataView _TourGroupDataTable { get; set; }
        //public int _Position { get; set; }
        //是否是查看
        public bool _LookupState { get; set; }
        
        private DataView _ScheduleDataView = null;

        private string _Remark = "";
        private string _PhoneNotify = "";
        private string _EndTime = "00:00:00";


        public TourGroupScheduleForm(DataView tourGroupDataTable)//,int rowID)
        {
            InitializeComponent(); 

            _TourGroupDataTable = tourGroupDataTable;
            //_Position = rowID;
            //界面初始化时，备注窗口隐藏，没有值，将备注值存在_Remark中
           _Remark = _TourGroupDataTable[0]["Remark"].ToString();
           _PhoneNotify = _TourGroupDataTable[0]["PhoneNotify"].ToString();
        }

        #region 团数据发生变化后的保存

        void _TourGroupDataTable_ColumnChanged(object sender, DataColumnChangeEventArgs e)
        {
            //检测是否存在同名的“团名称”
            if (TeamGroupCtrl.CheckExistSameTourgroupName(lblTourGroupID.Text, tbTourgroupName.Text))
            {
                MessageBox.Show("已经存在相同的团名，请修改团名称", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                tbTourgroupName.Focus();
                return;
            }
            //DataRowView drView = BindingContext[_TourGroupDataTable].Current as DataRowView;
            // if(drView.Row.HasVersion(DataRowVersion.Proposed)) 
            //{
            TourGroupEntity tgEntity = new TourGroupEntity()
            {
                //AccompanyNames = drView["AccompanyNames"].ToString(),
                AdultNum = int.Parse(tbAdultNum.Text),
                AccompanyNum = int.Parse(tbAccompanyNum.Text),

                Currency = tbCurrency.EditValue == DBNull.Value ? "人民币" : tbCurrency.EditValue.ToString(),
                ExchangeRate = tbExchangeRate.EditValue == DBNull.Value ? 0 : decimal.Parse(tbExchangeRate.EditValue.ToString()),
                CurrencyAmount = tbCurrencyAmount.EditValue == DBNull.Value ? 0 : decimal.Parse(tbCurrencyAmount.EditValue.ToString()),
                PriceMethod = tbPriceMethod.EditValue == DBNull.Value ? "按人" : tbPriceMethod.EditValue.ToString(),

                SaleCost = tbSaleCost.EditValue == DBNull.Value ? 0 : decimal.Parse(tbSaleCost.EditValue.ToString()),
                SalePrice = tbSalePrice.EditValue == DBNull.Value ? 0 : decimal.Parse(tbSalePrice.EditValue.ToString()),
                SaleTotalCost = tbSaleTotalCost.EditValue == DBNull.Value ? 0 : decimal.Parse(tbSaleTotalCost.EditValue.ToString()),
                SaleTotalPrice = tbSaleTotalPrice.EditValue == DBNull.Value ? 0 : decimal.Parse(tbSaleTotalPrice.EditValue.ToString()),
                BudgeTotalCost = tbBudgeTotalCost.EditValue == DBNull.Value ? 0 : decimal.Parse(tbBudgeTotalCost.EditValue.ToString()),
                BudgeTotalPrice = tbBudgeTotalPrice.EditValue == DBNull.Value ? 0 : decimal.Parse(tbBudgeTotalPrice.EditValue.ToString()),
                BuildGroupDate = tbBuildGroupDate.DateTime.ToString("yyyy-MM-dd"),
                ChildNum = int.Parse(tbChildNum.Text),
                Country = tbCountry.Text,
                CountryCode = lblCountryCode.Text,
                CustomerCode = tbCustomerCode.Text,
                CustomerName = lblCustomerName.Text,
                EndDate = tbEndDate.DateTime.ToString("yyyy-MM-dd"),
                Guesttype = cbGuesttype.Text,
                HasGuide = (ckHasGuide.Checked == true ? 1 : 0),
                StayOver = int.Parse(tbNightNum.Text),
                OwnerA = cbOwnerA.Text,
                OwnerB = cbOwnerB.Text,
                RealTotalCost = tbRealTotalCost.EditValue == DBNull.Value ? 0 : decimal.Parse(tbRealTotalCost.EditValue.ToString()),
                RealTotalPrice = tbRealTotalPrice.EditValue == DBNull.Value ? 0 : decimal.Parse(tbRealTotalPrice.EditValue.ToString()),
                //界面初始化时，备注窗口隐藏，没有值，将备注值存在_Remark中，如果没有打开备注窗口，则用该值写库。
                Remark = mbRemark.EditValue == null ? _Remark : mbRemark.EditValue.ToString(),
                PhoneNotify = mbPhoneNotify.EditValue == null ? _PhoneNotify : mbPhoneNotify.EditValue.ToString(),
                //RoomRemark = "",//drView["RoomRemark"].ToString(),
                Servicetype = cbServicetype.Text,
                StartDate = tbStartDate.DateTime.ToString("yyyy-MM-dd"),
                TourgroupID = lblTourGroupID.Text,
                TourgroupName = tbTourgroupName.Text,
                TourgroupState = lblTourGroupState.Text,
                Tourgrouptype = cbTourgrouptype.Text,
                ShouleEnterShop = (chkShouleEnterShop.Checked == true ? 1 : 0)
            };
            TeamGroupCtrl.UpdateTourGroup(tgEntity);
            //}
        }
        /// <summary>
        /// 国家信息改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbCountry_EditValueChanged(object sender, EventArgs e)
        {
            tbTourgroupName.EditValue = tbCountry.Text;
        }
        /// <summary>
        /// 起止日期变更
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbEndDate_EditValueChanged(object sender, EventArgs e)
        {
            if (tbEndDate.EditValue == null || tbStartDate.EditValue == null)
                return;

            tbNightNum.EditValue = (tbEndDate.DateTime - tbStartDate.DateTime).Days;

            if ((tbEndDate.DateTime - tbStartDate.DateTime).Days < 0)
                toolTipCtrl.ShowHint("请注意：  起始日期大于结束日期", sender as Control, DevExpress.Utils.ToolTipLocation.RightBottom);
            else
                toolTipCtrl.HideHint();
        }
        /// <summary>
        /// 国家信息变更
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listBoxCountry_Click(object sender, EventArgs e)
        {
            tbCountry.EditValue = listBoxCountry.Text;
            lblCountryCode.Text = listBoxCountry.SelectedValue.ToString();
            popupContainerControl1.OwnerEdit.ClosePopup();
        }
         /// <summary>
        /// 客户信息变更
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void customerGridView_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            tbCustomerCode.EditValue = customerGridView.GetRowCellValue(e.RowHandle, "CustomerID");
            lblCustomerName.Text = customerGridView.GetRowCellValue(e.RowHandle, "CustomerName").ToString();
            popupContainerControl2.OwnerEdit.ClosePopup();
        }

        /// <summary>
        /// 外币数额或汇率值变化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbExchangeRate_EditValueChanged(object sender, EventArgs e)
        {
            decimal exchangeRate = tbExchangeRate.EditValue == null ? 1 : decimal.Parse(tbExchangeRate.EditValue.ToString());
            decimal currencyAmount = tbCurrencyAmount.EditValue == null ? 0 : decimal.Parse(tbCurrencyAmount.EditValue.ToString());
            decimal adultNum = tbAdultNum.EditValue == null ? 0 : decimal.Parse(tbAdultNum.EditValue.ToString());
            tbSalePrice.EditValue = currencyAmount * exchangeRate;
            if (tbPriceMethod.EditValue.ToString() == TourgroupPriceMethod.按人.ToString())
                tbSaleTotalPrice.EditValue = decimal.Parse(tbSalePrice.EditValue.ToString()) * adultNum;
            else
                tbSaleTotalPrice.EditValue = tbSalePrice.EditValue;

        }
        private void tbSaleCost_EditValueChanged(object sender, EventArgs e)
        {
            decimal saleCost = tbSaleCost.EditValue == null ? 0 : decimal.Parse(tbSaleCost.EditValue.ToString());
            decimal adultNum = tbAdultNum.EditValue == null ? 0 : decimal.Parse(tbAdultNum.EditValue.ToString());
            if (tbPriceMethod.EditValue.ToString() == TourgroupPriceMethod.按人.ToString())
                tbSaleTotalCost.EditValue = saleCost * adultNum;
            else
                tbSaleTotalCost.EditValue = saleCost;
        }
        private void tbAdultNum_EditValueChanged(object sender, EventArgs e)
        {
            tbExchangeRate_EditValueChanged(sender,e);
            tbSaleCost_EditValueChanged(sender, e);
        }

        
        #endregion

        #region 窗口初始化
        //窗口Load事件
        private void TourGroupScheduleForm_Load(object sender, EventArgs e)
        {
            #region 查看状态处理
            
            pricePanel.Visible = !_LookupState;
            pricePanel1.Visible = !_LookupState;
            btnPrice.Enabled = !_LookupState;
            btnTourGroupState.Enabled = !_LookupState;
            
            #endregion
            
            #region 初始化国家下拉列表

            listBoxCountry.DataSource = BaseInfoCtrl.GetCountryData();
            listBoxCountry.DisplayMember = "CountryName";
            listBoxCountry.ValueMember = "CountryCode";

            //DataTable dvCountry = BaseInfoCtl.GetCountryData();
            //tbCountry.Properties.View.OptionsBehavior.AutoPopulateColumns = false;
            //tbCountry.Properties.DataSource = dvCountry;
            //tbCountry.Properties.DisplayMember = "CountryName";
            //tbCountry.Properties.ValueMember = "CountryCode";

            //GridColumn col1 = tbCountry.Properties.View.Columns.AddField("CountryCode");
            //col1.Caption = "国家编码";
            //col1.VisibleIndex = 0;

            //GridColumn col2 = tbCountry.Properties.View.Columns.AddField("CountryName");
            //col2.Caption = "国家名称";
            //col2.VisibleIndex = 1;


            //tbCountry.Properties.View.BestFitColumns();
            //tbCountry.Properties.PopupFormWidth = 300;
            #endregion

            #region 初始化客户下拉列表

            this.customerGridControl.DataSource = BaseInfoCtrl.GetCustomerData();
            
            #endregion

            #region 初始化‘组团人’下拉列表

            DataTable dt = UserInfoCtrl.GetUserInfoData();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                cbOwnerA.Properties.Items.Add(dt.Rows[i]["Name"]);
                cbOwnerB.Properties.Items.Add(dt.Rows[i]["Name"]);
            }
            cbOwnerA.Enabled = !_LookupState;
            cbOwnerB.Enabled = !_LookupState;

            #endregion

            //初始化团基本信息显示
            InitGui();
            //this.BindingContext[_TourGroupDataTable].Position = _Position;
            _TourGroupDataTable.Table.ColumnChanged += new DataColumnChangeEventHandler(_TourGroupDataTable_ColumnChanged);

            //初始化计划内容
            LoadScheduleGridViewData();


            #region 团状态按钮处理

            DataRowView drv = (BindingContext[_TourGroupDataTable].Current as DataRowView);
            switch (TeamGroupCtrl.GetTourGroupState(lblTourGroupID.Text))
            {
                case TeamStateEnum.计划:
                    btnTourGroupState.Text = "成行";
                    #region 团的费用状态
                    tbBudgeTotalCost.EditValue = drv["BudgeTotalCost"];
                    tbBudgeTotalPrice.EditValue = drv["BudgeTotalPrice"];
                    tbRealTotalCost.EditValue = drv["RealTotalCost"];
                    tbRealTotalPrice.EditValue = drv["RealTotalPrice"];
                    #endregion
                    break;
                case TeamStateEnum.成行:
                    btnTourGroupState.Text = "分配";
                    #region 团的费用状态
                    tbBudgeTotalCost.EditValue = drv["BudgeTotalCost"];
                    tbBudgeTotalPrice.EditValue = drv["BudgeTotalPrice"];
                    tbRealTotalCost.EditValue = drv["RealTotalCost"];
                    tbRealTotalPrice.EditValue = drv["RealTotalPrice"];
                    #endregion
                    tbTourgroupName.Enabled = false;
                    tbCountry.Enabled = false;
                    tbCurrencyAmount.Enabled = false;
                    tbExchangeRate.Enabled = false;
                    tbSaleCost.Enabled = false;
                    break;
                case TeamStateEnum.分配:
                    btnTourGroupState.Text = "审核";
                    #region 团的费用状态
                    tbBudgeTotalCost.EditValue = drv["BudgeTotalCost"];
                    tbBudgeTotalPrice.EditValue = drv["BudgeTotalPrice"];
                    tbRealTotalCost.EditValue = drv["RealTotalCost"];
                    tbRealTotalPrice.EditValue = drv["RealTotalPrice"];
                    #endregion
                    tbTourgroupName.Enabled = false;
                    tbCountry.Enabled = false;
                    tbCurrencyAmount.Enabled = false;
                    tbExchangeRate.Enabled = false;
                    tbSaleCost.Enabled = false;
                    break;
                case TeamStateEnum.取消:
                    btnAdd.Enabled = false;
                    btnDelete.Enabled = false;
                    btnTourGroupState.Enabled = false;
                    baseInfoPanel.Enabled = false;
                    ScheduleGridView.OptionsBehavior.Editable = false;
                    break;
                case TeamStateEnum.审核:
                case TeamStateEnum.终结:
                    btnAdd.Enabled = false;
                    btnDelete.Enabled = false;
                    btnTourGroupState.Enabled=false;
                    baseInfoPanel.Enabled = false;
                    mbRemark.Enabled = false;
                    mbPhoneNotify.Enabled = false;
                    ScheduleGridView.OptionsBehavior.Editable = false;
                    break;
                default:
                    break;
            }

            #endregion
        }

        //计划行程数据加载
        private void LoadScheduleGridViewData()
        {
            #region 初始化计划行程‘城市’单元格控件内容
            //提供‘城市’选择         
            //StartAndEndCityEdit.DataSource = BaseInfoCtrl.GetCityData();

            #endregion

            _ScheduleDataView = new DataView(TeamGroupCtrl.GetTourGroupSchedule(lblTourGroupID.Text).Tables[0]);
            scheduleGridControl.DataSource = _ScheduleDataView;

            //为行程计划网格‘视图’注册数据更新事件
            _ScheduleDataView.Table.RowDeleted += new DataRowChangeEventHandler(Table_RowDeleted);
            _ScheduleDataView.Table.RowChanged += new DataRowChangeEventHandler(Table_RowChanged);

            ScheduleGridView.FocusedRowHandle = ScheduleGridView.RowCount - 1;

        }

        //初始化界面内容
        private void InitGui()
        {

            //团状态信息
            lblTourGroupID.DataBindings.Add("Text", _TourGroupDataTable, "TourgroupID");
            lblTourGroupState.DataBindings.Add("Text", _TourGroupDataTable, "TourgroupState");


            tbCountry.DataBindings.Add("EditValue", _TourGroupDataTable, "Country");
            lblCountryCode.DataBindings.Add("Text", _TourGroupDataTable, "CountryCode");
            tbStartDate.DataBindings.Add("EditValue", _TourGroupDataTable, "StartDate");
            tbEndDate.DataBindings.Add("EditValue", _TourGroupDataTable, "EndDate");
            tbNightNum.DataBindings.Add("EditValue", _TourGroupDataTable, "StayOver");
            tbAdultNum.DataBindings.Add("EditValue", _TourGroupDataTable, "AdultNum");
            tbChildNum.DataBindings.Add("EditValue", _TourGroupDataTable, "ChildNum");
            tbTourgroupName.DataBindings.Add("EditValue", _TourGroupDataTable, "TourgroupName");
            cbGuesttype.DataBindings.Add("EditValue", _TourGroupDataTable, "Guesttype");
            cbServicetype.DataBindings.Add("EditValue", _TourGroupDataTable, "Servicetype");
            cbTourgrouptype.DataBindings.Add("EditValue", _TourGroupDataTable, "Tourgrouptype");
            tbAccompanyNum.DataBindings.Add("EditValue", _TourGroupDataTable, "AccompanyNum");
            tbCustomerCode.DataBindings.Add("EditValue", _TourGroupDataTable, "CustomerCode");
            lblCustomerName.DataBindings.Add("Text", _TourGroupDataTable, "CustomerName");
            cbOwnerA.DataBindings.Add("EditValue", _TourGroupDataTable, "OwnerA");
            cbOwnerB.DataBindings.Add("EditValue", _TourGroupDataTable, "OwnerB");
            ckHasGuide.DataBindings.Add("Checked", _TourGroupDataTable, "HasGuide");
            tbBuildGroupDate.DataBindings.Add("EditValue", _TourGroupDataTable, "BuildGroupDate");
            mbRemark.DataBindings.Add("EditValue", _TourGroupDataTable, "Remark");
            mbPhoneNotify.DataBindings.Add("EditValue", _TourGroupDataTable, "PhoneNotify");

            tbSaleCost.DataBindings.Add("EditValue", _TourGroupDataTable, "SaleCost");
            tbSalePrice.DataBindings.Add("EditValue", _TourGroupDataTable, "SalePrice");
            tbSaleTotalCost.DataBindings.Add("EditValue", _TourGroupDataTable, "SaleTotalCost");
            tbSaleTotalPrice.DataBindings.Add("EditValue", _TourGroupDataTable, "SaleTotalPrice");
            tbBudgeTotalCost.DataBindings.Add("EditValue", _TourGroupDataTable, "BudgeTotalCost");
            tbBudgeTotalPrice.DataBindings.Add("EditValue", _TourGroupDataTable, "BudgeTotalPrice");
            tbRealTotalCost.DataBindings.Add("EditValue", _TourGroupDataTable, "RealTotalCost");
            tbRealTotalPrice.DataBindings.Add("EditValue", _TourGroupDataTable, "RealTotalPrice");

            tbCurrency.DataBindings.Add("EditValue", _TourGroupDataTable, "Currency");
            tbCurrencyAmount.DataBindings.Add("EditValue", _TourGroupDataTable, "CurrencyAmount");
            tbExchangeRate.DataBindings.Add("EditValue", _TourGroupDataTable, "ExchangeRate");
            tbPriceMethod.DataBindings.Add("EditValue", _TourGroupDataTable, "PriceMethod");
            chkShouleEnterShop.DataBindings.Add("Checked", _TourGroupDataTable, "ShouleEnterShop");

            string rowState = _TourGroupDataTable[0]["TourgroupRowState"].ToString();//.Rows[_Position]["TourgroupRowState"].ToString();
            tbTourgroupRowState.Checked = (rowState == "2");
        } 
        #endregion

        #region 计划行程数据变化后的后台处理
        void Table_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            if (e.Action == DataRowAction.Change || e.Action == DataRowAction.ChangeCurrentAndOriginal || e.Action == DataRowAction.ChangeOriginal)
            {

                TourGroupScheduleEntity schedule = new TourGroupScheduleEntity();
                schedule.TourgroupID = this.lblTourGroupID.Text;
                schedule.Date = DateTime.Parse(e.Row["Date"].ToString()).ToString("yyyy-MM-dd");
                schedule.Time = DateTime.Parse(e.Row["Time"].ToString()).ToString("HH:mm:ss");
                schedule.StayOver = int.Parse(e.Row["StayOver"].ToString());
                schedule.Journeytype = e.Row["Journeytype"].ToString();
                schedule.StartCity = e.Row["StartCity"].ToString();
                schedule.DestinationCity = e.Row["DestinationCity"].ToString();
                schedule.TrafficType = e.Row["TrafficType"].ToString();
                schedule.Traffic = e.Row["Traffic"].ToString();
                schedule.TravelAgencyID = int.Parse(e.Row["TravelAgencyID"].ToString());
                schedule.TravelAgencyName = e.Row["TravelAgencyName"].ToString();
                schedule.Reception = e.Row["Reception"].ToString();
                schedule.TicketType = e.Row["TicketType"].ToString();
                schedule.Context = e.Row["Context"].ToString();
                schedule.Dining = e.Row["Dining"].ToString();
                schedule.Hotel = e.Row["Hotel"].ToString();
                schedule.HotelID = int.Parse(e.Row["HotelID"].ToString());
                schedule.Seat = e.Row["Seat"].ToString();
                schedule.ScheduleMethod = e.Row["ScheduleMethod"].ToString();

                schedule.TourGroupScheduleID = int.Parse(e.Row["TourGroupScheduleID"].ToString());

                TeamGroupCtrl.UpdateTourGroupSchedule(schedule);
            }
        }

        private void Table_RowDeleted(object sender, DataRowChangeEventArgs e)
        {
            if (e.Action == DataRowAction.Delete)
            {
                string tourGroupScheduleID = e.Row["TourGroupScheduleID", DataRowVersion.Original].ToString();
                if (tourGroupScheduleID == "")
                    return;

                int scheduleID = int.Parse(tourGroupScheduleID);
                //删除行程计划数据
                TeamGroupCtrl.DeleteTourGroupSchedule(scheduleID);
                //删除行程计划关联的宾馆、地接社、交通（火车、飞机、汽车）预定信息及费用主表
                HotelOrderCtrl.DeleteHotelOrder(scheduleID);
                TravelOrderCtrl.DeleteTravelOrder(scheduleID);
                
                //火车飞机预订由‘计调’来完成删除
                //TrainOrderCtrl.DeleteTrainOrder(scheduleID);
                //FlightOrderCtrl.DeleteFlightOrder(scheduleID);
            }
        }

        #endregion

        #region  火车、飞机生成新的或修改已有的预订及费用数据

        /// <summary>
        /// 火车生成新的或修改已有的预订及费用信息
        /// </summary>
        /// <param name="tourGroupScheduleId"></param>
        /// <param name="e"></param>
        private void SaveTrainOrderData(int tourGroupScheduleId, DataRow dr)
        {
            //清除已有火车或飞机预订信息
            //TrainOrderCtrl.DeleteTrainOrder(tourGroupScheduleId);          //同时删除存在此行程计划的火车预订，两种预订不能同时存在
            //FlightOrderCtrl.DeleteFlightOrder(tourGroupScheduleId);        //同时删除存在此行程计划的飞机预订，两种预订不能同时存在

            //DataTable dtTrainOrderData = TrainOrderCtrl.GetTrainOrderData(tourGroupScheduleId);
            //int expenseID = -1;

            //if (dtTrainOrderData != null && dtTrainOrderData.Rows.Count > 0)
            //    expenseID = int.Parse(dtTrainOrderData.Rows[0]["ExpenseID"].ToString());//取得费用标识

            string journeyType = dr["Journeytype"].ToString();//ScheduleGridView.GetRowCellValue(ScheduleGridView.FocusedRowHandle, "Journeytype").ToString();
            string time = DateTime.Parse(dr["Time"].ToString()).ToString("HH:mm:ss");
            string date = DateTime.Parse(dr["Date"].ToString()).ToString("yyyy-MM-dd");

            //创建火车预定信息内容
            TrainOrderEntity trainOrder = new TrainOrderEntity();
            trainOrder.OrderState = OrderStateEnum.未订.ToString();/*重点内容，初始化订单状态为‘未定’*/
            trainOrder.TrainCode = dr["Traffic"].ToString();
            trainOrder.BeginPosition = dr["StartCity"].ToString();
            trainOrder.EndPosition = dr["DestinationCity"].ToString();
            switch (EnumHelper.Journey_Str2Enum(journeyType, true))
            {
                case JourneyTypeEnum.入境:
                case JourneyTypeEnum.抵:
                    trainOrder.StartTime = "00:00:00";
                    trainOrder.EndTime = time;
                    break;
                case JourneyTypeEnum.离境:
                case JourneyTypeEnum.离:
                    trainOrder.StartTime = time;
                    trainOrder.EndTime = "00:00:00";
                    break;
                default:
                    break;
            }
            trainOrder.StartDate = date;
            trainOrder.EndDate = date;
            trainOrder.HardSeatQuantity = 0;
            trainOrder.SoftSeatQuantity = 0;
            trainOrder.HardSleeperBottomQuantity = 0;
            trainOrder.HardSleeperMiddleQuantity = 0;
            trainOrder.HardSleeperTopQuantity = 0;
            trainOrder.HighBoxQuantity=0;
            trainOrder.ChildSeatQuantity = 0;
            trainOrder.Remark = "";
            
            trainOrder.SoftSleeperBottomPrice=0;
            trainOrder.SoftSleeperBottomQuantity=0;
            trainOrder.SoftSleeperTopPrice=0;
            trainOrder.SoftSleeperTopQuantity=0;
            trainOrder.HandlingCharge = 0;
            trainOrder.HardSeatPrice = 0;
            trainOrder.ChildSeatPrice=0;
            trainOrder.HardSleeperTopPrice = 0;
            trainOrder.HardSleeperMiddlePrice = 0;
            trainOrder.SoftSeatPrice = 0;
            trainOrder.HardSleeperBottomPrice = 0;
            trainOrder.HighBoxPrice = 0;

            trainOrder.AccompanyNum = int.Parse(tbAccompanyNum.EditValue.ToString());
            trainOrder.AdultNum = int.Parse(tbAdultNum.EditValue.ToString());
            trainOrder.ChildNum = int.Parse(tbChildNum.EditValue.ToString());
            trainOrder.TourgroupID = lblTourGroupID.Text;
            trainOrder.TourgroupName=tbTourgroupName.Text;
            trainOrder.TourGroupScheduleID=tourGroupScheduleId;
            trainOrder.ProviderID = -1;
            trainOrder.ProviderName = "";

            trainOrder.Seat = dr["Seat"].ToString();

            //创建费用
            ExpenseEntity expense = new ExpenseEntity()
            {
                //ExpenseID = _ExpenseID,
                TourgroupID = lblTourGroupID.Text,
                TourgroupName = TeamGroupCtrl.GetTeamGroupNameById(lblTourGroupID.Text),
                ProviderID = -1,
                ProviderName = "",
                ServiceName = dr["StartCity"].ToString() + "-" + dr["DestinationCity"].ToString() + " 火车票",
                Budget = 0,
                PayTotal = 0,
                ApplyPayTotal = 0,
                AdjustAmount = 0,
                Status = ExpenseStatusEnum.计划.ToString(),
                TypeBelong = ProviderTypeEnum.火车票.ToString(),
                ApplyPay = 0,
                PayStatus = PayApplyStatusEnum.未付.ToString(),
                CreateByUserName = Thread.CurrentPrincipal.Identity.Name, //UserInfoCtrl.GetNameByUserName(Thread.CurrentPrincipal.Identity.Name)
                TourGroupScheduleID = tourGroupScheduleId,
                CreateTime = DateTime.Now.ToString("yyyy-MM-dd"),
                ExpenseTypeID = 4,//所属费用类型(费用类型表中存储着编号，此编号是固定的，1房费、2团费、3餐费、4交通费、5门票、6杂费)
                ExpenseType = BaseInfoCtrl.GetExpenseTypeNameByID(4)//同上
           };
            TrainOrderCtrl.CreateTrainOrderAndExpenseData(expense, trainOrder);
        } 
        
        /// <summary>
        /// 飞机生成新的或修改已有的预订及费用信息
        /// </summary>
        /// <param name="tourGroupScheduleId"></param>
        /// <param name="e"></param>
        private void SaveFlightOrderData(int tourGroupScheduleId, DataRow dr)
        {

            string journeyType = dr["Journeytype"].ToString();//ScheduleGridView.GetRowCellValue(ScheduleGridView.FocusedRowHandle, "Journeytype").ToString();
            string time = DateTime.Parse(dr["Time"].ToString()).ToString("HH:mm:ss");
            string date = DateTime.Parse(dr["Date"].ToString()).ToString("yyyy-MM-dd");

            //创建飞机预定信息内容
            FlightOrderEntity flightOrder = new FlightOrderEntity();
            flightOrder.OrderState = OrderStateEnum.未订.ToString();/*重点内容，初始化订单状态为‘未定’*/
            flightOrder.FlightCode = dr["Traffic"].ToString();
            flightOrder.AccompanyNum = int.Parse(tbAccompanyNum.EditValue.ToString());
            flightOrder.AdultNum = int.Parse(tbAdultNum.EditValue.ToString());
            flightOrder.BabyNum = 0;//int.Parse(tbBabyNum.EditValue.ToString())
            flightOrder.ChildNum = int.Parse(tbChildNum.EditValue.ToString());
            //flightOrder.AdultQuantity=0;
            //flightOrder.ChildQuantity=0;
            //flightOrder.BabyQuantity=0;
            //flightOrder.AccompanyQuantity=0;
            flightOrder.BeginPosition = dr["StartCity"].ToString(); //ScheduleGridView.GetRowCellValue(ScheduleGridView.FocusedRowHandle, "StartCity").ToString();
            flightOrder.EndPosition = dr["DestinationCity"].ToString(); //ScheduleGridView.GetRowCellValue(ScheduleGridView.FocusedRowHandle, "DestinationCity").ToString();
            flightOrder.StartDate = date;
            flightOrder.EndDate = date;

            switch (EnumHelper.Journey_Str2Enum(journeyType, true))
            {
                case JourneyTypeEnum.入境:
                case JourneyTypeEnum.抵:
                    flightOrder.StartTime = "00:00:00";
                    flightOrder.EndTime = time;
                    break;
                case JourneyTypeEnum.离境:
                case JourneyTypeEnum.离:
                    flightOrder.StartTime = time;
                    flightOrder.EndTime = "00:00:00";
                    break;
                default:
                    break;
            }
            flightOrder.Remark = "";
            flightOrder.AccompanyUnitPrice = 0;
            flightOrder.AdultUnitPrice = 0;
            flightOrder.BabyUnitPrice = 0;
            flightOrder.ChildUnitPrice = 0;
            flightOrder.HandlingCharge = 0;
            //FlightID=0;
            flightOrder.TourGroupScheduleID = tourGroupScheduleId;
            flightOrder.TourgroupID = lblTourGroupID.Text;
            flightOrder.TourgroupName = tbTourgroupName.Text;
            flightOrder.ProviderID = -1;
            flightOrder.ProviderName = "";

            flightOrder.Seat = dr["Seat"].ToString();
            
            //创建费用
            ExpenseEntity expense = new ExpenseEntity()
            {
                //ExpenseID = _ExpenseID,
                TourgroupID = lblTourGroupID.Text,
                TourgroupName=TeamGroupCtrl.GetTeamGroupNameById(lblTourGroupID.Text),
                ProviderID = -1,
                ProviderName = "",
                ServiceName = dr["StartCity"].ToString()+"-"+dr["DestinationCity"].ToString()+" 飞机票",
                Budget = 0,
                PayTotal = 0,
                ApplyPayTotal = 0,
                AdjustAmount = 0,
                Status = ExpenseStatusEnum.计划.ToString(),
                TypeBelong = ProviderTypeEnum.飞机票.ToString(),
                ApplyPay=0,
                PayStatus= PayApplyStatusEnum.未付.ToString(),
                CreateByUserName = Thread.CurrentPrincipal.Identity.Name,//UserInfoCtrl.GetNameByUserName(Thread.CurrentPrincipal.Identity.Name)
                TourGroupScheduleID = tourGroupScheduleId,
                CreateTime = DateTime.Now.ToString("yyyy-MM-dd"),
                ExpenseTypeID = 4,//所属费用类型(费用类型表中存储着编号，此编号是固定的，1房费、2团费、3餐费、4交通费、5门票、6杂费)
                ExpenseType = BaseInfoCtrl.GetExpenseTypeNameByID(4)//同上
            };
            FlightOrderCtrl.CreateFlightOrderAndExpenseData(expense, flightOrder);
        }  
        
        #endregion

        #region 窗口底部系列按钮事件处理

        //新建行程计划
        private void btnAdd_Click(object sender, EventArgs e)
        {
            TourGroupScheduleEntity schedule = new TourGroupScheduleEntity();
            schedule.TourgroupID = lblTourGroupID.Text;
            schedule.Time = "00:00:00";
            schedule.StayOver = 1;
            schedule.TravelAgencyID = -1;
            schedule.HotelID = -1;
            schedule.Dining = "午晚";
            //schedule.Seat = "软卧";

            if (ScheduleGridView.RowCount > 0)
            {
                //新增的日期=上行日期+上行过夜数
                int StayOver = int.Parse(ScheduleGridView.GetRowCellDisplayText(ScheduleGridView.RowCount - 1, "StayOver"));
                schedule.Date = DateTime.Parse(ScheduleGridView.GetRowCellDisplayText(ScheduleGridView.RowCount - 1, "Date")).AddDays(StayOver).ToString("yyyy-MM-dd");//上一条日期+过夜数
                //检测上行‘抵’‘离’状态
                string Journeytype = ScheduleGridView.GetRowCellDisplayText(ScheduleGridView.RowCount - 1, "Journeytype").ToString();
                if (!string.IsNullOrEmpty(Journeytype))
                {
                    switch (EnumHelper.Journey_Str2Enum(Journeytype, true))
                    {
                        case JourneyTypeEnum.入境:
                        case JourneyTypeEnum.离境:
                            schedule.Journeytype = "";
                            break;
                        case JourneyTypeEnum.抵:
                            schedule.Journeytype = JourneyTypeEnum.离.ToString();
                            schedule.StartCity = ScheduleGridView.GetRowCellDisplayText(ScheduleGridView.RowCount - 1, "DestinationCity").ToString();
                            break;
                        case JourneyTypeEnum.离:
                            schedule.Journeytype = JourneyTypeEnum.抵.ToString();
                            schedule.StartCity = ScheduleGridView.GetRowCellDisplayText(ScheduleGridView.RowCount - 1, "StartCity").ToString();
                            schedule.DestinationCity = ScheduleGridView.GetRowCellDisplayText(ScheduleGridView.RowCount - 1, "DestinationCity").ToString();
                            schedule.TrafficType = ScheduleGridView.GetRowCellDisplayText(ScheduleGridView.RowCount - 1, "TrafficType").ToString();
                            schedule.Traffic = ScheduleGridView.GetRowCellDisplayText(ScheduleGridView.RowCount - 1, "Traffic").ToString();
                            schedule.Time = _EndTime=="" ? "00:00:00" : _EndTime;
                            _EndTime = "00:00:00";
                            break;
                        default:

                            break;
                    }
                }else
                    schedule.Journeytype = "入境";

            }
            else
                schedule.Date = tbStartDate.DateTime.ToString("yyyy-MM-dd");

            TeamGroupCtrl.CreateTourGroupSchedule(schedule);

            //刷新网格
            LoadScheduleGridViewData();
        }
        //删除行程计划
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (ScheduleGridView.FocusedRowHandle >= 0)
            {
                if (MessageBox.Show("确定删除选中计划信息吗？", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    string tourGroupScheduleID = ScheduleGridView.GetDataRow(ScheduleGridView.FocusedRowHandle)["TourGroupScheduleID"].ToString();
                    if (tourGroupScheduleID == "")
                        return;
                    DataTable ds = ExpensesCtrl.GetExpenseDataByScheduleID(int.Parse(tourGroupScheduleID), new ProviderTypeEnum[] { 
                            ProviderTypeEnum.餐厅,ProviderTypeEnum.火车票,ProviderTypeEnum.飞机票,
                            ProviderTypeEnum.其它,ProviderTypeEnum.汽车,ProviderTypeEnum.景点,ProviderTypeEnum.演出
                        });
                    if (ds.Rows.Count > 0)
                    {
                        MessageBox.Show("已存在其他相关预订，请计调删除相关预订后才能删除", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        tbTourgroupName.Focus();
                        return;
                    }

                    if (TeamGroupCtrl.CheckExistPayApply(tourGroupScheduleID, ""))
                    {
                        MessageBox.Show("已经申请付款，不能删除", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        tbTourgroupName.Focus();
                        return;
                    }
                    
                    ScheduleGridView.GetDataRow(ScheduleGridView.GetSelectedRows()[0]).Delete();//取得第一行选中数据
                    ScheduleGridView.Focus();//激活GridView控件，引发Table_RowDeleted完成删除工作
                }
            }
        }
        //打印
        private void btnPrint_Click(object sender, EventArgs e)
        {
            new SchedulePrintForm(lblTourGroupID.Text).ShowDialog(this);
        }
        //备注
        private void btnRemark_Click(object sender, EventArgs e)
        {
            panelRemark.Visible = true;
        }
        private void btnRemarkClose_Click(object sender, EventArgs e)
        {
            panelRemark.Visible = false;
        }
        private void btnPhoneNotify_Click(object sender, EventArgs e)
        {
            panelPhoneNotify.Visible = true;
        }
        private void btnPhoneNotifyClose_Click(object sender, EventArgs e)
        {
            panelPhoneNotify.Visible = false;
        }
        /// <summary>
        /// 变更通知
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnChangeNotify_Click(object sender, EventArgs e)
        {
            ChangeNotifyForm changeNofityForm = new ChangeNotifyForm(lblTourGroupID.Text);
            changeNofityForm.ShowDialog(this);
        }
        /// <summary>
        /// 客人列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGuestList_Click(object sender, EventArgs e)
        {
            GuestListForm guestListForm = new GuestListForm(lblTourGroupID.Text);
            guestListForm.ShowDialog(this);
        }

        private void btnLookGuide_Click(object sender, EventArgs e)
        {
            new GuideStatusLookForm(lblTourGroupID.Text).ShowDialog(this);
        }
        private void btnRestaurant_Click(object sender, EventArgs e)
        {
            new RestaurantOrderStatusLookForm(lblTourGroupID.Text).ShowDialog(this);
        }
        private void btnAuditBill_Click(object sender, EventArgs e)
        {
            BillForm billForm = new BillForm();
            billForm._TourgroupID = lblTourGroupID.Text;
            billForm.ShowDialog(this);
        }
        private void btnCash_Click(object sender, EventArgs e)
        {
            new CashApplyForm(lblTourGroupID.Text).ShowDialog(this);
        }
        /// <summary>
        /// 查看销售报价信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void btnSalePrice_Click(object sender, EventArgs e)
        //{
            //new SalePriceForm(lblTourGroupID.Text).ShowDialog(this);
        //}
        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }
        private void btnPrice_Click(object sender, EventArgs e)
        {
            new TeamGroupExpenseManagerForm(_ScheduleDataView, lblTourGroupID.Text, lblTourGroupState.Text).ShowDialog(this);

            //刷新审核价格和审核成本
            DataTable tourDt = TeamGroupCtrl.GetTeamGroupRowData(lblTourGroupID.Text);
            tbBudgeTotalCost.Text = tourDt.Rows[0]["BudgeTotalCost"].ToString();
            tbBudgeTotalPrice.Text = tourDt.Rows[0]["BudgeTotalPrice"].ToString();
        }
        private void tbTourgroupRowState_CheckedChanged(object sender, EventArgs e)
        {
            if (tbTourgroupRowState.Checked)//团已处理
                TeamGroupCtrl.UpdateTourGroupTourgroupRowState(lblTourGroupID.Text, 2);
            else//去掉则置为团计划已经拷贝过来
                TeamGroupCtrl.UpdateTourGroupTourgroupRowState(lblTourGroupID.Text, 1);
        }
        private void mnuLookEvaluate_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (e.Item.Name)
            {
                case "mnuHotel":
                    new HotelEvaluateForm(lblTourGroupID.Text).ShowDialog(this);
                    break;
                case "mnuGuide":
                    new GuideEvaluateForm(lblTourGroupID.Text).ShowDialog(this);
                    break;
                case "mnuRestaurant":
                    new RestaurantEvaluateForm(lblTourGroupID.Text).ShowDialog(this);
                    break;
                case "mnuVehicle":
                    new VehicleEvaluateForm(lblTourGroupID.Text).ShowDialog(this);
                    break;
                default:
                    break;
            }
        }

        #endregion

        #region 行程计划GridView事件处理

        private void StartAndEndCityEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            //暂时屏蔽，用LookUpEdit提供的城市的选择方式
            DevExpress.XtraEditors.ButtonEdit btnEdit = sender as DevExpress.XtraEditors.ButtonEdit;
            CitySelectedToolForm city = new CitySelectedToolForm();

            if (city.ShowDialog(this) == DialogResult.OK)
                btnEdit.EditValue = city.ReturnCityName;
        }

        private void TrafficEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            string TrafficType = ScheduleGridView.GetRowCellValue(ScheduleGridView.FocusedRowHandle, ScheduleGridView.Columns["TrafficType"]).ToString();
            string tourGroupScheduleID = ScheduleGridView.GetDataRow(ScheduleGridView.FocusedRowHandle)["TourGroupScheduleID"].ToString();

            if (string.IsNullOrEmpty(TrafficType))
            {
                
                MessageBox.Show("您还没有选择交通工具类型！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            DevExpress.XtraEditors.ButtonEdit btnEdit = sender as DevExpress.XtraEditors.ButtonEdit;
            switch (EnumHelper.Traffic_Str2Enum(TrafficType, true))//CommonEnum.GetTrafficType(TrafficType))
            {
                case TrafficTypeEnum.飞机:
                    FlightOrderForm flightOrderForm = new FlightOrderForm()
                    {
                        _StartCity=ScheduleGridView.GetRowCellValue(ScheduleGridView.FocusedRowHandle, ScheduleGridView.Columns["StartCity"]).ToString(),
                        _EndCity=ScheduleGridView.GetRowCellValue(ScheduleGridView.FocusedRowHandle, ScheduleGridView.Columns["DestinationCity"]).ToString(),
                    };
                    if (flightOrderForm.ShowDialog(this) == DialogResult.OK)//设置各项返回值到表格中
                    {
                        btnEdit.EditValue = flightOrderForm._FlightCode;
                        //ScheduleGridView.SetRowCellValue(ScheduleGridView.FocusedRowHandle, "StartCity", flightOrderForm._StartCity);
                        //ScheduleGridView.SetRowCellValue(ScheduleGridView.FocusedRowHandle, "DestinationCity", flightOrderForm._EndCity);
                        string journeyType = ScheduleGridView.GetRowCellValue(ScheduleGridView.FocusedRowHandle, "Journeytype").ToString();
                        switch (EnumHelper.Journey_Str2Enum(journeyType, true))
                        {
                            case JourneyTypeEnum.入境:
                            case JourneyTypeEnum.抵:
                                ScheduleGridView.SetRowCellValue(ScheduleGridView.FocusedRowHandle, "Time", flightOrderForm._EndTime);
                                break;
                            case JourneyTypeEnum.离境:
                            case JourneyTypeEnum.离:
                                ScheduleGridView.SetRowCellValue(ScheduleGridView.FocusedRowHandle, "Time", flightOrderForm._StartTime);
                                _EndTime = flightOrderForm._EndTime;
                                break;
                            default:
                                break;
                        }
                    }
                    break;
                case TrafficTypeEnum.火车:
                    TrainOrderForm trainOrderForm = new TrainOrderForm()
                    {
                        _StartCity = ScheduleGridView.GetRowCellValue(ScheduleGridView.FocusedRowHandle, ScheduleGridView.Columns["StartCity"]).ToString(),
                        _EndCity = ScheduleGridView.GetRowCellValue(ScheduleGridView.FocusedRowHandle, ScheduleGridView.Columns["DestinationCity"]).ToString(),
                    };
                    if (trainOrderForm.ShowDialog(this) == DialogResult.OK)//设置各项返回值到表格中
                    {
                        btnEdit.EditValue = trainOrderForm._TrainCode;
                        //ScheduleGridView.SetRowCellValue(ScheduleGridView.FocusedRowHandle, "StartCity", trainOrderForm._StartCity);
                        //ScheduleGridView.SetRowCellValue(ScheduleGridView.FocusedRowHandle, "DestinationCity", trainOrderForm._EndCity);
                        string journeyType = ScheduleGridView.GetRowCellValue(ScheduleGridView.FocusedRowHandle, "Journeytype").ToString();
                        switch (EnumHelper.Journey_Str2Enum(journeyType, true))
                        {
                            case JourneyTypeEnum.入境:
                            case JourneyTypeEnum.抵:
                                ScheduleGridView.SetRowCellValue(ScheduleGridView.FocusedRowHandle, "Time", trainOrderForm._EndTime);
                                break;
                            case JourneyTypeEnum.离境:
                            case JourneyTypeEnum.离:
                                ScheduleGridView.SetRowCellValue(ScheduleGridView.FocusedRowHandle, "Time", trainOrderForm._StartTime);
                                _EndTime = trainOrderForm._EndTime;
                                break;
                            default:
                                break;
                        }
                    }
                    break;
                case TrafficTypeEnum.汽车:
                    MessageBox.Show("请自行填写‘汽车’服务信息！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;
                default:
                    MessageBox.Show("您选择的交通工具类型目前不被支持！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;
            }
            
        }

        private void TravelAgencyNameEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            string tourGroupScheduleID = ScheduleGridView.GetDataRow(ScheduleGridView.FocusedRowHandle)["TourGroupScheduleID"].ToString();
            string destinationCity = ScheduleGridView.GetDataRow(ScheduleGridView.FocusedRowHandle)["DestinationCity"].ToString();

            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Delete)
            {
                if (BillCtrl.IsExistBillData(tourGroupScheduleID))
                {
                    MessageBox.Show("存在地接社提交的“对账单数据，不能删除", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (MessageBox.Show("确认删除供应商吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    if (TeamGroupCtrl.CheckExistPayApply(tourGroupScheduleID, ProviderTypeEnum.旅行社.ToString()))
                    {
                        MessageBox.Show("已经申请付款，不能删除", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        tbTourgroupName.Focus();
                        return;
                    }
                    
                    DevExpress.XtraEditors.ButtonEdit btnEdit = sender as DevExpress.XtraEditors.ButtonEdit;
                    btnEdit.Tag = -1;
                    btnEdit.EditValue = "";
                    ScheduleGridView.SetRowCellValue(ScheduleGridView.FocusedRowHandle, "TravelAgencyID", -1);
                    ScheduleGridView.SetRowCellValue(ScheduleGridView.FocusedRowHandle, "Reception", "");
                    TravelOrderCtrl.DeleteTravelOrder(int.Parse(tourGroupScheduleID));
                }
            }
            else
            {
                if (TeamGroupCtrl.CheckExistPayApply(tourGroupScheduleID, ProviderTypeEnum.旅行社.ToString()))
                {
                    MessageBox.Show("已经申请付款，不能修改", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    tbTourgroupName.Focus();
                    return;
                } 
                TravelOrderForm travelForm = new TravelOrderForm(destinationCity)
                {
                    _TourGroupID = lblTourGroupID.Text,
                    _TourGroupState = lblTourGroupState.Text,
                    _TourGroupScheduleID = int.Parse(tourGroupScheduleID),
                    _AdultNum = int.Parse(tbAdultNum.Text)
                };
                if (travelForm.ShowDialog(this) == DialogResult.OK)
                {
                    DevExpress.XtraEditors.ButtonEdit btnEdit = sender as DevExpress.XtraEditors.ButtonEdit;
                    btnEdit.EditValue = travelForm.ReturnTravelAgencyName;
                    ScheduleGridView.SetRowCellValue(ScheduleGridView.FocusedRowHandle, "TravelAgencyID", travelForm.ReturnTravelAgencyID);
                    ScheduleGridView.SetRowCellValue(ScheduleGridView.FocusedRowHandle, "Reception", travelForm.ReturnContact);
                }
            }
            //刷新审核价格和审核成本
            DataTable tourDt = TeamGroupCtrl.GetTeamGroupRowData(lblTourGroupID.Text);
            tbBudgeTotalCost.Text = tourDt.Rows[0]["BudgeTotalCost"].ToString();
            tbBudgeTotalPrice.Text = tourDt.Rows[0]["BudgeTotalPrice"].ToString();

        }

        private void HotelEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            string tourGroupScheduleID = ScheduleGridView.GetDataRow(ScheduleGridView.FocusedRowHandle)["TourGroupScheduleID"].ToString();
            string destinationCity = ScheduleGridView.GetDataRow(ScheduleGridView.FocusedRowHandle)["DestinationCity"].ToString();
            DateTime startDate = DateTime.Parse(ScheduleGridView.GetDataRow(ScheduleGridView.FocusedRowHandle)["Date"].ToString());
            string stayOver = ScheduleGridView.GetDataRow(ScheduleGridView.FocusedRowHandle)["StayOver"].ToString();

            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Delete)
            {
                if (MessageBox.Show("确认删除供应商吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    if (TeamGroupCtrl.CheckExistPayApply(tourGroupScheduleID, ProviderTypeEnum.宾馆.ToString()))
                    {
                        MessageBox.Show("已经申请付款，不能删除", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        tbTourgroupName.Focus();
                        return;
                    }

                    
                    DevExpress.XtraEditors.ButtonEdit btnEdit = sender as DevExpress.XtraEditors.ButtonEdit;
                    btnEdit.Tag = -1;
                    btnEdit.EditValue = "";
                    ScheduleGridView.SetRowCellValue(ScheduleGridView.FocusedRowHandle, "HotelID", -1);
                    ScheduleGridView.SetRowCellValue(ScheduleGridView.FocusedRowHandle, "ScheduleMethod", "");
                    HotelOrderCtrl.DeleteHotelOrder(int.Parse(tourGroupScheduleID));

                }
            }
            else
            {
                if (TeamGroupCtrl.CheckExistPayApply(tourGroupScheduleID, ProviderTypeEnum.宾馆.ToString()))
                {
                    MessageBox.Show("已经申请付款，不能修改", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    tbTourgroupName.Focus();
                    return;
                }
                HotelOrderForm hotelForm = new HotelOrderForm(destinationCity)
                {
                    _TourGroupID = lblTourGroupID.Text,
                    _TourGroupState = lblTourGroupState.Text,
                    _TourGroupScheduleID = int.Parse(tourGroupScheduleID),
                    _ArrivalTime = startDate,
                    _StayOver = int.Parse(stayOver)
                };
                if (hotelForm.ShowDialog(this) == DialogResult.OK)
                {
                    DevExpress.XtraEditors.ButtonEdit btnEdit = sender as DevExpress.XtraEditors.ButtonEdit;
                    ScheduleGridView.SetRowCellValue(ScheduleGridView.FocusedRowHandle, "HotelID", hotelForm._ReturnHotelID);
                    ScheduleGridView.SetRowCellValue(ScheduleGridView.FocusedRowHandle, "ScheduleMethod", hotelForm._ReturnScheduleMethod);
                    btnEdit.EditValue = hotelForm._ReturnHotelName;
                }
            }
            //刷新审核价格和审核成本
            DataTable tourDt = TeamGroupCtrl.GetTeamGroupRowData(lblTourGroupID.Text);
            tbBudgeTotalCost.Text = tourDt.Rows[0]["BudgeTotalCost"].ToString();
            tbBudgeTotalPrice.Text = tourDt.Rows[0]["BudgeTotalPrice"].ToString();

        }



        #endregion

        #region 行程计划窗口关闭
        
        private void TourGroupScheduleForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //激发行程计划的GrideView数据更新
            if (ScheduleGridView.FocusedRowModified)
                ScheduleGridView.FocusedRowHandle = ScheduleGridView.FocusedRowHandle == 0 ? 1 : 0;

            //激发团数据更新,转移一下焦点即可
            baseInfoPanel.Focus();
            //if (tbAccompanyNum.Focused)
            //    tbAdultNum.Focus();
            //else
            //    tbAccompanyNum.Focus();
        }

        #endregion

        #region 行数据校验

        private void ScheduleGridView_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            DataRowView dr = e.Row as DataRowView;
            if (dr["Journeytype"].ToString() == "")
                return;

            if (JourneyTypeEnum.离 == EnumHelper.Journey_Str2Enum(dr["Journeytype"].ToString(), true) || JourneyTypeEnum.离境 == EnumHelper.Journey_Str2Enum(dr["Journeytype"].ToString(), true))
            {
                if (dr["Traffic"].ToString() == "")
                {
                    ScheduleGridView.SetColumnError(ScheduleGridView.Columns["Traffic"], "车次信息不能为空", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Default);
                    e.Valid = false;
                }
                if (dr["TrafficType"].ToString() == "")
                {
                    ScheduleGridView.SetColumnError(ScheduleGridView.Columns["TrafficType"], "交通工具不能为空", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Default);
                    e.Valid = false;
                }
                if (dr["TicketType"].ToString() == "")
                {
                    ScheduleGridView.SetColumnError(ScheduleGridView.Columns["TicketType"], "订票信息不能为空", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Default);
                    e.Valid = false;
                }
                if (dr["Seat"].ToString() == "")
                {
                    ScheduleGridView.SetColumnError(ScheduleGridView.Columns["Seat"], "席位信息不能为空", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Default);
                    e.Valid = false;
                }
            }
        }

        private void ScheduleGridView_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                DataRowView dr = e.Row as DataRowView;

                if (dr["Traffic"].ToString() == "" || dr["TrafficType"].ToString() == "" || dr["TicketType"].ToString() == "" || dr["Seat"].ToString() == "")
                //{
                    //MessageBox.Show("您所填写的行内容不完整\n　请填写完整", "错误", MessageBoxButtons.OK, MessageBoxIcon.Question);
                    e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
                //}
                //else
                //    e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
            }
        }
        #endregion

        #region 团成行、审核按钮处理
        private void btnTourGroupState_Click(object sender, EventArgs e)
        {
            TicketTypeEnum tType;
            string trafficType;
            int tourGroupScheduleId;

            TeamStateEnum state = EnumHelper.Team_Str2Enum(lblTourGroupState.Text, true);

            switch (state)
            {
                case TeamStateEnum.计划:

                    #region 检测并处理团状态

                    if (tbSaleTotalPrice.EditValue == DBNull.Value || decimal.Parse(tbSaleTotalPrice.EditValue.ToString()) == 0 || tbSaleTotalCost.EditValue == DBNull.Value || decimal.Parse(tbSaleTotalCost.EditValue.ToString()) == 0)
                    {
                        MessageBox.Show("请输入预算价格和预算成本", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    if (MessageBox.Show("确认将团“成行”吗？", "成行确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        if (TeamGroupCtrl.UpdateTourGroupState(lblTourGroupID.Text, TeamStateEnum.成行) == 1)
                        {
                            lblTourGroupState.Text = TeamStateEnum.成行.ToString();//刷新
                            btnTourGroupState.Text = TeamStateEnum.分配.ToString();
                            pricePanel.Enabled = false;//价格面板不可用
                            tbTourgroupName.Enabled = false;//成行后团名不能修改
                        }
                    }
                    else
                        return;
                    #endregion

                    #region 根据销售预算生成团费

                    //写入团费（计划收入项中添加一条团应收的费用项）
                    
                    IncomeItemEntity icomeItem = new IncomeItemEntity()
                    {
                        TourgroupID = lblTourGroupID.Text,
                        TourgroupName = tbTourgroupName.Text,
                        CustomerName = lblCustomerName.Text,
                        IncomeItem = "团费",
                        PlanPrice = decimal.Parse(tbSaleTotalPrice.EditValue.ToString()),
                        ReceivedPrice = 0,
                        AdjustPrice = 0,
                        Remark = "",
                        Currency=tbCurrency.Text,
                        CurrencyAmount = (tbCurrencyAmount.EditValue == null ? 0 : decimal.Parse(tbCurrencyAmount.Text)) * (tbPriceMethod.Text == TourgroupPriceMethod.按人.ToString() ? decimal.Parse(tbAdultNum.Text) : 1),
                        ExchangeRate = tbExchangeRate.EditValue == null ? 1 : decimal.Parse(tbExchangeRate.Text)
                          
                    };
                    IncomeItemCtrl.CreateIncomeItemData(icomeItem);
                    //更新团审核价格
                    TeamGroupCtrl.UpdateTourGroupBudgePrice(lblTourGroupID.Text);

                    tbBudgeTotalPrice.EditValue = tbSaleTotalPrice.EditValue;

                    #endregion

                    #region 生成火车、飞机的订单信息

                    _ScheduleDataView.Table.AcceptChanges();
                    foreach (DataRow dr in _ScheduleDataView.Table.Rows)
                    {
                        if (dr["TicketType"].ToString() == "" || dr["TrafficType"].ToString() == "") continue;

                        tType = EnumHelper.Ticket_Str2Enum(dr["TicketType"].ToString(), true);
                        trafficType = dr["TrafficType"].ToString();
                        tourGroupScheduleId = int.Parse(dr["TourGroupScheduleID"].ToString());

                        //订票是‘自订’，并且存在交通类型，根据交通类型生成预订及费用数据
                        if (TicketTypeEnum.自订 == tType && trafficType != "")
                            switch (EnumHelper.Traffic_Str2Enum(trafficType, true))
                            {
                                case TrafficTypeEnum.飞机:
                                    SaveFlightOrderData(tourGroupScheduleId, dr);                   //根据计划号生成飞机预订及费用信息
                                    break;
                                case TrafficTypeEnum.火车:
                                    SaveTrainOrderData(tourGroupScheduleId, dr);                   //根据计划号生成火车预订及费用信息
                                    break;
                                default:
                                    break;
                            }
                    }

                    #endregion                    

                    MessageBox.Show("团“成行”操作成功！", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;
                case TeamStateEnum.成行:
                    if (MessageBox.Show("确认将团‘分配’通过吗？", "分配确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        //修改团状态为‘分配’
                        if (TeamGroupCtrl.UpdateTourGroupState(lblTourGroupID.Text, TeamStateEnum.分配) == 1)
                        {
                            lblTourGroupState.Text = TeamStateEnum.分配.ToString();//刷新
                            
                            baseInfoPanel.Enabled = false;//团信息面板不可用
                            btnTourGroupState.Text = TeamStateEnum.分配.ToString();
                            MessageBox.Show("团“分配”完成！", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    break;
                case TeamStateEnum.分配:
                    if (MessageBox.Show("确认将团‘审核’通过吗？", "审核确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        //检测所有的费用状态是否存在‘计划’或‘导游报销’项
                        if (ExpensesCtrl.GetAllExpenseStatusForPendingAudit(lblTourGroupID.Text) == true)
                        {
                            MessageBox.Show("团中部分费用未提交审核，请提醒相关人员提交审核！", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                        //修改审核价格、审核成本，三处（团审核、收款录入、新增付款）完成此动作-已实时计算，不用在此刷新
                        //TeamGroupCtrl.UpdateTourGroupBudge(lblTourGroupID.Text);
                        //修改团状态为‘审核’
                        if (TeamGroupCtrl.UpdateTourGroupState(lblTourGroupID.Text, TeamStateEnum.审核) == 1)
                        {
                            ExpensesCtrl.UpdateExpenseStatusAudit(lblTourGroupID.Text);

                            lblTourGroupState.Text = TeamStateEnum.审核.ToString();//刷新

                            //更新团审核价格和审核成本
                            TeamGroupCtrl.UpdateTourGroupBudgePrice(lblTourGroupID.Text);
                            TeamGroupCtrl.UpdateTourGroupBudgeCost(lblTourGroupID.Text);

                            //刷新审核价格和审核成本
                            DataTable tourDt = TeamGroupCtrl.GetTeamGroupRowData(lblTourGroupID.Text);
                            tbBudgeTotalCost.Text = tourDt.Rows[0]["BudgeTotalCost"].ToString();
                            tbBudgeTotalPrice.Text = tourDt.Rows[0]["BudgeTotalPrice"].ToString();

                            baseInfoPanel.Enabled = false;//团信息面板不可用
                            btnTourGroupState.Enabled = false;

                            MessageBox.Show("团“审核”操作成功！", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    break;

                default:
                    break;
            }
        }
        #endregion

        #region 备注框可移动
        Point mouse_Remarkoffset;

        private void panelRemark_MouseDown(object sender, MouseEventArgs e)
        {
            mouse_Remarkoffset = new Point(-e.X, -e.Y);
        }

        private void panelRemark_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Point mousePos = Control.MousePosition;
                mousePos.Offset(mouse_Remarkoffset.X, mouse_Remarkoffset.Y);
                ((Control)sender).Location = ((Control)sender).Parent.PointToClient(mousePos);
            }
        }
        #endregion

        #region 电话通知框可移动
        Point mouse_PhoneNotifyoffset;

        private void panelPhoneNotify_MouseDown(object sender, MouseEventArgs e)
        {
            mouse_PhoneNotifyoffset = new Point(-e.X, -e.Y);
        }

        private void panelPhoneNotify_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Point mousePos = Control.MousePosition;
                mousePos.Offset(mouse_PhoneNotifyoffset.X, mouse_PhoneNotifyoffset.Y);
                ((Control)sender).Location = ((Control)sender).Parent.PointToClient(mousePos);
            }
        }
        #endregion
    }
}
